//shoppinglist functions
var db_name = "shoppinglist";
var db_version = "1.0";
var db_display_name = "Shopping List";
var db_size = 1000000; //in bytes


 // Wait for Cordova to load
    //
    document.addEventListener("deviceready", onDeviceReady, false);

    // Populate the database 
    //
    function populateDB(tx) {
        //tx.executeSql('DROP TABLE IF EXISTS SHOPPING_LIST');
        tx.executeSql('CREATE TABLE IF NOT EXISTS SHOPPING_LIST (id INTEGER PRIMARY KEY, item_name, isRemoved DEFAULT false)');
        
    }

    // Query the database
    //
    function showShoppingListQuery(tx) {
        tx.executeSql('SELECT * FROM SHOPPING_LIST ORDER BY id DESC', [], showShoppingListSuccess, errorCB);
    }

    // Query the success callback
    //
    function showShoppingListSuccess(tx, results) {
        var len = results.rows.length;
        console.log("ShoppingList table: " + len + " rows found.");
        if (len==0){
        	$('#shoppinglist-items').html("Notes:<br/>- Tap on 'Add Item' button to add an shoppinglist item.<br />- You can tap on the item to cross it off.<br />- To completely delete an item, tap on the delete button on the right-hand side");
        	
        }else{
	        var s = "";
	        for (var i=0; i<len; i++){
	            if(results.rows.item(i).isRemoved=="true"){
	            	s += "<li id='shoppinglist-item-"+results.rows.item(i).id+"' class='crossed-shoppinglist'>" +
	            			"<a href='#' style='color:black;' onClick='recover("+results.rows.item(i).id+");'>"+results.rows.item(i).item_name+"</a>" +
	            			"<a href='javascript:deleteItem("+results.rows.item(i).id+")'>delete</a>" +
	            		 "</li>";
	            }else{
	            	s += "<li id='shoppinglist-item-"+results.rows.item(i).id+"'>" +
	            			"<a href='#' onClick='remove("+results.rows.item(i).id+");'>"+results.rows.item(i).item_name+"</a>" +
	            			"<a href='javascript:deleteItem("+results.rows.item(i).id+")'>delete</a>" +
	            		 "</li>";
	            }
	            //$('#shoppinglist-items').append("<li id='shoppinglist-item-"+results.rows.item(i).id+"'><a href='#' onClick='remove("+results.rows.item(i).id+");'>"+results.rows.item(i).item_name+" isRemoved:"+results.rows.item(i).isRemoved+"</a></li>");
				$('#shoppinglist-items').html(s);
				
	        }
        }
        //$('#shoppinglist-items').listview();
    	$('#shoppinglist-items').listview('refresh');
        
    }

    // Transaction error callback
    //
    function errorCB(err) {
        console.log("Error processing SQL: "+err.code);
    }

    // Transaction success callback
    //
    function successCB() {
        db.transaction(showShoppingListQuery, errorCB);
    }

    /************************
     * remove shopping list item functions
     * 
     ************************/
	function remove(id){
		console.log("removing id = "+id);
		//query db to update item status to removed
		db.transaction(function(tx){
			removeItemQuery(tx, id);
			}, errorCB);

	}
	
    //set isRemoved status in db
    function removeItemQuery(tx, id) {
        tx.executeSql('UPDATE SHOPPING_LIST SET isRemoved="true" WHERE id=?', [id], successCB, errorCB);
    }


    /************************
     * recover shopping list item functions
     * 
     ************************/
	function recover(id){
		console.log("recovering id = "+id);
		//query db to update item status to removed
		db.transaction(function(tx){
			recoverItemQuery(tx, id);
			}, errorCB);

	}
	
    //set isRemoved status in db
    function recoverItemQuery(tx, id) {
        tx.executeSql('UPDATE SHOPPING_LIST SET isRemoved="false" WHERE id=?', [id], 
        		function(tx, results){
        			recoverItemQuerySuccess(tx, results, id)
        		}, errorCB);
    }

    // Query the success callback
    //
    function recoverItemQuerySuccess(tx, results, id) {
        console.log('recovering item ('+id+') succeeded.');
        //$("shoppinglist-item-"+id).removeClass('crossed-shoppinglist');
        successCB();
    }	

    
    
    /********************
     * add item functions
     */
    
    function addItem(item_name){
        db.transaction(function(tx) {
        	addItemQuery(tx, item_name);
        }, errorCB);    
    }
    
    function addItemQuery(tx, item_name){
    	//alert(item_name);
        tx.executeSql('INSERT INTO SHOPPING_LIST (item_name) VALUES (?)',[item_name],successCB,errorCB);
    }
    
    /**
     * delete item functions
     */
    function deleteItem(id){
        db.transaction(function(tx) {
        	deleteItemQuery(tx, id);
        }, errorCB);    
    }
    
    function deleteItemQuery(tx, id){
    	//alert(item_name);
        tx.executeSql('DELETE FROM SHOPPING_LIST WHERE id=?',[id],successCB,errorCB);
    }
    
    /**
     * empty list functions
     */
    
    function emptyShoppingList(){
        db.transaction(emptyShoppingListQuery, errorCB);    
    }
    
    function emptyShoppingListQuery(tx){
    	//alert(item_name);
        tx.executeSql('DELETE FROM SHOPPING_LIST',[],successCB,errorCB);
    }
    
    // process the confirmation dialog result
    function onEmptylistConfirm(button) {
        if(button==1){//first button(OK) selected
        	emptyShoppingList();
        }
    }

    // Show a custom confirmation dialog
    //
    function showEmptyListConfirm() {
        navigator.notification.confirm(
            'Do you really want to empty the shoppinglist?',  // message
            onEmptylistConfirm,              // callback to invoke with index of button pressed
            'Empty Shoppinglist',            // title
            'OK,CANCEL'          // buttonLabels
        );
    }
    
$(document).delegate('#add-item-dialog', 'click', function() {
	createDialog('#add-item-dialog');
	}
);
$(document).delegate('#add-item-dialog2', 'click', function() {
	createDialog('#add-item-dialog2');
	}
);

function createDialog(element) {
	  // NOTE: The selector can be whatever you like, so long as it is an HTML element.
	  //       If you prefer, it can be a member of the current page, or an anonymous div
	  //       like shown.
	  $(element).simpledialog2({
	    mode: 'button',
	    headerText: 'New Item',
	    headerClose: false,
	    buttonPrompt: 'Enter Item Name Here:',
	    buttonInput: true,
	    buttons : {
	      'OK': {
	        click: function () { 

	        	var itemName = $.trim($.mobile.sdLastInput);
	        	if(itemName!=''){
	  	          addItem(itemName);
		          console.log(itemName);
	        	}else{
	        		console.log($.mobile.sdLastInput);
	        	}
	        }
	      },
	      'CANCEL': {
	          click: function () { 
	        	  console.log('cancelled.');
	          },
	          icon: "delete",
	          theme: "c"
	        }
	    }
	  })
	}